package com.tsingteng.cosfun.ui.found;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.pili.droid.shortvideo.PLShortVideoUploader;
import com.qiniu.pili.droid.shortvideo.PLUploadResultListener;
import com.qiniu.pili.droid.shortvideo.PLUploadSetting;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.base.BasePresenterActivity;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.utils.FileUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.ImageViewUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SunAwardActivity extends BasePresenterActivity<SunPresenter, SunContact.ISunView> implements TextWatcher, SunContact.ISunView, PLUploadResultListener {
    @BindView(R.id.tv_report_sun)
    TitleView mTvReportSun;
    @BindView(R.id.et_sun_describe)
    EditText mEtSunDescribe;
    @BindView(R.id.rv_rv_sun)
    RecyclerView mRvRvSun;
    @BindView(R.id.ll_sun_camera)
    LinearLayout mllSunCamera;
    @BindView(R.id.tv_sun_number)
    TextView mtvSunNumber;
    @BindView(R.id.btn_commit_sun)
    TextView mBtnCommitSun;
    private List<String> picList = new ArrayList<>();
    private int count = 0;
    private List<String> urlPic = new ArrayList<>();
    long activityId;
    private UpLoadReportAdapter upLoadReportAdapter;
    private PLShortVideoUploader mVideoUploadManager;
    private String path;
    private String domain;
    private String sign;
    private int index = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sun_award;
    }

    @Override
    protected void getIntentData(Intent intent) {
        isFound =true;
        NotchUtil.setWindowTrans(this, false, false);
        activityId = intent.getLongExtra(Constant.ACTIVITYID, 0);
    }

    @Override
    protected void initData() {
        for (int i = 0; i < 5; i++) {
            urlPic.add("");
        }
        mTvReportSun.setTitle(getResources().getString(R.string.sun_award));
        mTvReportSun.setIvLeft(R.drawable.back_big_icon);
        mRvRvSun.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        upLoadReportAdapter = new UpLoadReportAdapter();
        mRvRvSun.setAdapter(upLoadReportAdapter);
        mEtSunDescribe.setCursorVisible(false);
        PLUploadSetting uploadSetting = new PLUploadSetting();
        mVideoUploadManager = new PLShortVideoUploader(AppContext.getContext(), uploadSetting);
        mVideoUploadManager.setUploadResultListener(this);
        mEtSunDescribe.addTextChangedListener(this);
        mTvReportSun.setOnTitleClickListener(new TitleView.OnTitleClickListener() {
            @Override
            public void onLeft() {
                finish();
            }

            @Override
            public void onRight() {

            }

            @Override
            public void onRight2() {

            }
        });
//        mBtnCommitSun.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String content = mEtSunDescribe.getText().toString();
//                mPresenter.pull(activityId,content,picList);
//            }
//        });
//        mllSunCamera.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ImageViewUtils.starPhoto(this,false);
//            }
//        });
    }

    @OnClick({R.id.btn_commit_sun, R.id.ll_sun_camera,R.id.et_sun_describe})
    void onclick(View view) {
        switch (view.getId()) {
            case R.id.et_sun_describe:
                mEtSunDescribe.setCursorVisible(true);
                break;
            case R.id.btn_commit_sun:
                if (picList.size() == 0) {
                    ToastUtils.showToast(getResources().getString(R.string.choice_pic));
                    return;
                }
                if (0 == index) {
                    index = 1;
                    mPresenter.loginUploadSeven();
                }
                break;
            case R.id.ll_sun_camera:
                ImageViewUtils.starPhoto(this, true);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String imagePath;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCut()) {
                        imagePath = localMedia.getCutPath();
                    } else if (localMedia.isCompressed()) {
                        imagePath = localMedia.getCompressPath();
                    } else {
                        imagePath = localMedia.getPath();
                    }
                    picList.add(imagePath);
                    resetView();
                    break;
            }
        }
    }

    @Override
    protected SunPresenter createPresenter() {
        return new SunPresenter();
    }

    public void resetView() {
        mtvSunNumber.setText(picList.size() + "/4");
        upLoadReportAdapter.getData().clear();
        upLoadReportAdapter.addData(picList);
        upLoadReportAdapter.notifyDataSetChanged();
        mllSunCamera.setVisibility(picList.size() == 4 ? View.GONE : View.VISIBLE);

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String etString = mEtSunDescribe.getText().toString().trim();
        if (etString.length() == 200) {
            Toast.makeText(this, getResources().getString(R.string.message_limit), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showSun() {

        ToastUtils.showToast("上传成功");
        finish();
    }

    @Override
    public void showUploadSeven(VideoSignBean videoSignBean) {
        path = videoSignBean.getPath();
        domain = videoSignBean.getDomain();
        sign = videoSignBean.getSign();
        try {
            FileInputStream fileInputStream = new FileInputStream(picList.get(0));
            String fileName = FileUtils.getFileMD5(fileInputStream);
            mVideoUploadManager.startUpload(picList.get(0), path + "/" + fileName + ".jpg", sign);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUploadVideoSuccess(JSONObject jsonObject) {
        try {
            final String filePath = domain + "/" + jsonObject.getString("key");
            LogUtils.i(filePath + "0000000000000000");
            urlPic.set(count, filePath);
            count++;
            if (count > picList.size() - 1) {
                //说明已经上传完成
                if (null == mEtSunDescribe){
                    return;
                }
                String content = mEtSunDescribe.getText().toString();
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < urlPic.size(); i++) {
                    if (i == urlPic.size() - 1) {
                        stringBuilder.append(urlPic.get(i));
                    } else {
                        stringBuilder.append(urlPic.get(i)).append(";");
                    }
                }
                mPresenter.pull(activityId, content, stringBuilder.toString());
                return;
            }
            FileInputStream fileInputStream = null;

            fileInputStream = new FileInputStream(picList.get(count));
            String fileName = FileUtils.getFileMD5(fileInputStream);
            mVideoUploadManager.startUpload(picList.get(count), path + "/" + fileName + ".jpg", sign);
//            mVideoUploadManager.startUpload(picList.get(count), path + "/" + String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).hashCode(), sign);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUploadVideoFailed(int i, String s) {

    }

    public class UpLoadReportAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public UpLoadReportAdapter() {
            super(R.layout.item_upload_report_adapter);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            ImageView imageView = helper.getView(R.id.iv_report_third);
            ImageUtils.LoadImage(mContext, item, imageView);
            helper.getView(R.id.delete_image_view_third).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    picList.remove(item);
                    resetView();
                }
            });
        }
    }
}
